using System;
using System.Collections;

namespace RideMe.Core.SortableCollection
{
    public class Comparer : IComparer
    {
        string _sortPropertyName;
        SortDirection _sortDirection;

        public Comparer(string sortPropertyName)
        {
            this._sortPropertyName = sortPropertyName;
            this._sortDirection = SortDirection.Asc;
            // default to ascending order
        }

        public Comparer(string sortPropertyName, SortDirection sortDirection)
        {
            this._sortPropertyName = sortPropertyName;
            this._sortDirection = sortDirection;
        }

        public int Compare(object x, object y)
        {
            // Get the values of the relevant property on the x and y objects

            object valueOfX = x.GetType().GetProperty(_sortPropertyName).GetValue(x, null);
            object valueOfY = y.GetType().GetProperty(_sortPropertyName).GetValue(y, null);

            IComparable comp = valueOfY as IComparable;

            // Flip the value from whatever it was to the opposite.
            return Flip(comp.CompareTo(valueOfX));
        }

        private int Flip(int i)
        {
            return (i * (int)_sortDirection);
        }
    }
}
